<?php
namespace Qy {
    /**
    * 企业微信第三方应用接口类
    * @author Jamers
    * @since 2017.1.1
    * @see http://qydev.weixin.qq.com/wiki/index.php?title=%E7%AC%AC%E4%B8%89%E6%96%B9%E5%BA%94%E7%94%A8%E6%8E%A5%E5%8F%A3%E8%AF%B4%E6%98%8E
    */
    class Service {
        private $common;
        private $suite_access_token;
        public $suite_id, $suite_secret, $suite_ticket;
        
        public function __construct($ary = array()) {
            if (isset($ary['common'])) {
                $this->common = &$ary['common'];
            }else{
                $this->common = new \Qy\Common();
            }
        }
        
        public function init_suite($suite_id = '', $suite_secret = '', $suite_ticket = '') {
            if ($suite_id) $this->suite_id = $suite_id;
            if ($suite_secret) $this->suite_secret = $suite_secret;
            if ($suite_ticket) $this->suite_ticket = $suite_ticket;
        }
        
        /**
        * 获取应用套件令牌
        * @see http://qydev.weixin.qq.com/wiki/index.php?title=%E7%AC%AC%E4%B8%89%E6%96%B9%E5%BA%94%E7%94%A8%E6%8E%A5%E5%8F%A3%E8%AF%B4%E6%98%8E
        * 
        * @param mixed $suite_id
        * @param mixed $suite_secret
        * @param mixed $suite_ticket
        */
        private function get_remote_suite_token($suite_id, $suite_secret, $suite_ticket) {
            if (empty($suite_id) || empty($suite_secret) || empty($suite_ticket)) return false;
            $data = array('suite_id' => $suite_id, 'suite_secret' => $suite_secret, 'suite_ticket' => $suite_ticket);
            $url = "https://qyapi.weixin.qq.com/cgi-bin/service/get_suite_token";
            $ret = $this->common->httpRequest($url, $data, 'post');
            if (isset($ret['suite_access_token'])) {
                $this->suite_access_token = $ret['suite_access_token'];
                $this->saveAccessToken($suite_id, $suite_secret, $ret['suite_access_token']);
            }
            return $ret['suite_access_token'];
        }
        /**
        * 获取suite_token
        * 
        * @param mixed $suite_id
        * @param mixed $suite_secret
        * @param mixed $suite_ticket
        */
        public function get_suite_token($suite_id = '', $suite_secret = '', $suite_ticket = '') {
            if (empty($suite_id)) $suite_id = $this->suite_id;
            if (empty($suite_secret)) $suite_secret = $this->suite_secret;
            if (empty($suite_ticket)) $suite_ticket = $this->suite_ticket;
            $result = $this->getLocalAccessToken($suite_id, $suite_secret);
            if (empty($result)) {
                if (empty($suite_ticket)) throw new Exception('suite_ticket mission.');
                $result = $this->get_remote_suite_token($suite_id, $suite_secret, $suite_ticket);
                if (empty($result)) {
                    return FALSE;
                }else{
                    return $result;
                }
            }else{
                return $result;
            }
        }
        
        /**
        * 获取预授权码
        * @see http://qydev.weixin.qq.com/wiki/index.php?title=%E7%AC%AC%E4%B8%89%E6%96%B9%E5%BA%94%E7%94%A8%E6%8E%A5%E5%8F%A3%E8%AF%B4%E6%98%8E
        * 
        * @param mixed $suite_id
        * @param mixed $s_a_token
        */
        public function get_pre_auth_code($suite_id, $s_a_token = '') {
            if (empty($suite_id)) return false;
            if (empty($s_a_token)) $s_a_token = $this->get_suite_token();
            $data = array('suite_id' => $suite_id);
            $url = "https://qyapi.weixin.qq.com/cgi-bin/service/get_pre_auth_code?suite_access_token={$s_a_token}";
            return $this->common->httpRequest($url, $data, 'post');
        }
        
        
        private function saveAccessToken($suite_id, $suite_secret, $token) {
            if (empty($suite_id) || empty($suite_secret) || empty($token)) {
                return FALSE;
            }
            if (!file_exists(dirname(__FILE__) . '/suite_token.bin')) {
                file_put_contents(dirname(__FILE__) . '/suite_token.bin', "");
            }

            $result = file_get_contents(dirname(__FILE__) . '/suite_token.bin');

            $result = json_decode($result, TRUE);
            $key = md5($suite_id . $suite_secret);

            if ($result) {
                //清除过期AccessToken
                foreach ($result as $k => $v) {
                    if (time() - 7200 > $v[1]) unset($result[$k]);
                }
            }
            $result[$key] = array($token, time());

            if (file_put_contents(dirname(__FILE__) . '/suite_token.bin', json_encode($result))) {
                return TRUE;
            } else {
                return FALSE;
            }
        }
        
        private function getLocalAccessToken($corpid = FALSE, $corpsecret = FALSE) {
            if (empty($corpid) || empty($corpsecret)) {
                return FALSE;
            }

            if (!file_exists(dirname(__FILE__) . '/suite_token.bin')) {
                return FALSE;
            }

            $result = file_get_contents(dirname(__FILE__) . '/suite_token.bin');
            if (empty($result)) {
                return FALSE;
            }

            $result = json_decode($result, TRUE);
            $key = md5($corpid . $corpsecret);
            if (isset($result[$key])) {
                if (time() - 7200 > $result[$key][1]) {
                    // token已超时
                    return FALSE;
                } else {
                    // token未超时
                    return $result[$key][0];
                }
            } else {
                return FALSE;
            }
        }
        
        /**
        * 设置授权配置
        * @see http://qydev.weixin.qq.com/wiki/index.php?title=%E7%AC%AC%E4%B8%89%E6%96%B9%E5%BA%94%E7%94%A8%E6%8E%A5%E5%8F%A3%E8%AF%B4%E6%98%8E
        * 
        * @param mixed $pre_auth_code
        * @param mixed $appid
        * @param mixed $auth_type
        * @param mixed $s_a_token
        */
        public function set_session_info($pre_auth_code,$appid = array(), $auth_type = 0, $s_a_token = '') {
            if (empty($pre_auth_code)) return false;
            if (empty($s_a_token)) $s_a_token = $this->get_suite_token();
            $data = array('pre_auth_code' => $pre_auth_code,);
            $tmp = array();
            if ($appid) $tmp['appid'] = $appid;
            $tmp['auth_type'] = $auth_type;
            $data['session_info'] = $tmp;
            $url = "https://qyapi.weixin.qq.com/cgi-bin/service/set_session_info?suite_access_token={$s_a_token}";
            return $this->common->httpRequest($url, $data, 'post');
        }
        
        /**
        * 获取企业号的永久授权码
        * @see http://qydev.weixin.qq.com/wiki/index.php?title=%E7%AC%AC%E4%B8%89%E6%96%B9%E5%BA%94%E7%94%A8%E6%8E%A5%E5%8F%A3%E8%AF%B4%E6%98%8E#.E8.8E.B7.E5.8F.96.E4.BC.81.E4.B8.9A.E5.8F.B7.E7.9A.84.E6.B0.B8.E4.B9.85.E6.8E.88.E6.9D.83.E7.A0.81
        * 
        * @param mixed $suite_id
        * @param mixed $auth_code
        * @param mixed $s_a_token
        */
        public function get_permanent_code($suite_id, $auth_code, $s_a_token = '') {
            if (emyty($auth_code)) return false;
            if (empty($suite_id)) $suite_id = $this->suite_id;
            if (empty($s_a_token)) $s_a_token = $this->get_suite_token();
            $url = "https://qyapi.weixin.qq.com/cgi-bin/service/get_permanent_code?suite_access_token={$s_a_token}";
            $data = array('suite_id' => $suite_id, 'auth_code' => $auth_code);
            return $this->common->httpRequest($url, $data, 'post');
        }
        /**
        * 获取企业号的授权信息
        * @see http://qydev.weixin.qq.com/wiki/index.php?title=%E7%AC%AC%E4%B8%89%E6%96%B9%E5%BA%94%E7%94%A8%E6%8E%A5%E5%8F%A3%E8%AF%B4%E6%98%8E#.E8.8E.B7.E5.8F.96.E4.BC.81.E4.B8.9A.E5.8F.B7.E7.9A.84.E6.8E.88.E6.9D.83.E4.BF.A1.E6.81.AF
        * 
        * @param mixed $suite_id
        * @param mixed $auth_corpid
        * @param mixed $permanent_code
        * @param mixed $s_a_token
        */
        public function get_auth_info($suite_id, $auth_corpid, $permanent_code, $s_a_token = '') {
            if (empty($permanent_code)) return false;
            if (empty($suite_id)) $suite_id = $this->suite_id;
            if (empty($auth_corpid)) $auth_corpid = $this->common->corpid;
            if (empty($s_a_token)) $s_a_token = $this->get_suite_token();
            $data = array('suite_id' => $suite_id, 'auth_corpid' => $auth_corpid, 'permanent_code' => $permanent_code);
            $url = "https://qyapi.weixin.qq.com/cgi-bin/service/get_auth_info?suite_access_token={$s_a_token}";
            return $this->common->httpRequest($url, $data, 'post');
        }
        
        /**
        * 获取企业号access_token
        * @see http://qydev.weixin.qq.com/wiki/index.php?title=%E7%AC%AC%E4%B8%89%E6%96%B9%E5%BA%94%E7%94%A8%E6%8E%A5%E5%8F%A3%E8%AF%B4%E6%98%8E#.E8.8E.B7.E5.8F.96.E4.BC.81.E4.B8.9A.E5.8F.B7access_token
        * 
        * @param mixed $suite_id
        * @param mixed $auth_corpid
        * @param mixed $permanent_code
        * @param mixed $s_a_token
        */
        private function get_remote_corp_token($suite_id, $auth_corpid, $permanent_code, $s_a_token = '') {
            if (empty($permanent_code)) return false;
            if (empty($suite_id)) $suite_id = $this->suite_id;
            if (empty($auth_corpid)) $auth_corpid = $this->common->corpid;
            if (empty($s_a_token)) $s_a_token = $this->get_suite_token();
            $data = array('suite_id' => $suite_id, 'auth_corpid' => $auth_corpid, 'permanent_code' => $permanent_code);
            $url = "https://qyapi.weixin.qq.com/cgi-bin/service/get_corp_token?suite_access_token={$s_a_token}";
            $ret = $this->common->httpRequest($url, $data, 'post');
            if (empty($ret)) {
                return FALSE;
            }else{
                $this->saveAccessToken($suite_id, $auth_corpid, $ret['access_token']);
                return $ret['access_token'];
            }
        }
        
        /**
        * 读取企业AccessToken
        * 
        * @param mixed $suite_id
        * @param mixed $auth_corpid
        * @param mixed $permanent_code
        * @param mixed $s_a_token
        */
        public function get_core_token($suite_id='', $auth_corpid='', $permanent_code='', $s_a_token = '') {
            if (empty($suite_id)) $suite_id = $this->suite_id;
            if (empty($auth_corpid)) $auth_corpid = $this->common->corpid;
            $ret = $this->getLocalAccessToken($suite_id, $auth_corpid);
            if (empty($ret)) {
                $ret = $this->get_remote_corp_token($suite_id, $auth_corpid, $permanent_code, $s_a_token);
                if (empty($ret)) {
                    return FALSE;
                }else{
                    return $ret;
                }
            }else{
                return $ret;
            }
        }
        
        /**
        * 通讯录同步
        * @see http://qydev.weixin.qq.com/wiki/index.php?title=%E7%AC%AC%E4%B8%89%E6%96%B9%E5%BA%94%E7%94%A8%E6%8E%A5%E5%8F%A3%E8%AF%B4%E6%98%8E#.E9.80.9A.E8.AE.AF.E5.BD.95.E5.90.8C.E6.AD.A5
        * 
        * @param mixed $seq
        * @param mixed $offset
        * @param mixed $a_token
        */
        public function getPageSync($seq = 0, $offset = 0, $a_token = '') {
            if (empty($a_token)) $a_token = $this->get_core_token();
            if (empty($a_token)) return false;
            $data = array('seq' => $seq, 'offset' => $offset);
            $url = "https://qyapi.weixin.qq.com/cgi-bin/sync/getpage?access_token={$a_token}";
            return $this->common->httpRequest($url, $data, 'post');
        }

        /**
        * 获取应用提供商凭证
        * @see http://qydev.weixin.qq.com/wiki/index.php?title=%E7%AE%A1%E7%90%86%E5%90%8E%E5%8F%B0%E5%8D%95%E7%82%B9%E7%99%BB%E5%BD%95
        * 
        * @param mixed $corpid
        * @param mixed $provider_secret
        */
        public function get_provider_token($corpid, $provider_secret) {
            if (empty($provider_secret)) return false;
            if (empty($corpid)) $corpid = $this->common->corpid;
            $data = array('corpid' => $corpid, 'provider_secret' => $provider_secret);
            $url = "https://qyapi.weixin.qq.com/cgi-bin/service/get_provider_token";
            return $this->common->httpRequest($url, $data, 'post');
        }
    }
}